package com.talking.view;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.MenuItem;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.github.dhaval2404.imagepicker.ImagePicker;
import com.talking.App;
import com.talking.R;
import com.talking.adapter.GroupMemberAdapter;
import com.talking.bean.UserBean;
import com.talking.databinding.ActivityGroupSettingBinding;
import com.talking.model.Http;
import com.talking.presenter.GroupPresenter;
import com.talking.utils.Utils;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class GroupSettingActivity extends AppCompatActivity {
    private ActivityGroupSettingBinding binding;
    private GroupMemberAdapter adp;
    private final List<UserBean> data=new ArrayList<>();
    private ActivityResultLauncher<Intent> launcher;
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (android.R.id.home==item.getItemId()){ finish(); }
        return super.onOptionsItemSelected(item);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding=ActivityGroupSettingBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        Glide.with(this).load(Http.BASE_URL+ App.groupBean.groupIcon).apply(Utils.getGlideOption()).placeholder(R.drawable.loading).placeholder(R.drawable.loading).error(R.drawable.loaderr).into(binding.groupSettingIcon);
        binding.groupSettingEdit.setText(App.groupBean.groupName);
        binding.groupSettingIcon.setOnClickListener(v -> {
            ImagePicker.with(this).cropSquare().compress(1024).maxResultSize(1080, 1080).saveDir(getExternalCacheDir().toString() + "icon").createIntent(intent -> {
                launcher.launch(intent);
                return null;
            });
        });
        binding.groupSettingModify.setOnClickListener(v -> {
            if (binding.groupSettingEdit.isEnabled()){
                if (binding.groupSettingEdit.getText().toString().equals("")){
                    Utils.toast( "请输入群名称");
                }else {
                    binding.groupSettingEdit.setEnabled(false);
                    GroupPresenter.updateNameById(App.groupBean.id, binding.groupSettingEdit.getText().toString(), new Callback() {
                        @Override
                        public void onFailure(@NotNull Call call, @NotNull IOException e) {
                            e.printStackTrace();
                        }
                        @Override
                        public void onResponse(@NotNull Call call, @NotNull Response response) {
                        }
                    });
                    binding.groupSettingModify.setText("修改");
                }
            }else {
                binding.groupSettingEdit.setEnabled(true);
                binding.groupSettingModify.setText("提交");
            }
        });
        binding.groupSettingInvitation.setOnClickListener(v -> {
            startActivity(new Intent(GroupSettingActivity.this,InvitationActivity.class));
        });
        adp=new GroupMemberAdapter(this,data);
        binding.groupSettingMember.setAdapter(adp);
        binding.groupSettingExit.setOnClickListener(v -> {
            GroupPresenter.exitGroup(App.sp.getString("account", ""),App.groupBean.id, new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    e.printStackTrace();
                }
                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) {
                   runOnUiThread(() -> {
                       setResult(4);
                       finish();
                   });
                }
            });
        });
        binding.groupSettingMember.setOnItemClickListener((parent, view, position, id) -> {
            App.userBean= data.get(position);
            startActivity(new Intent(GroupSettingActivity.this,PersonActivity.class));
        });
        GroupPresenter.queryAllMember(App.groupBean.id, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
            }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) {
                runOnUiThread(() -> {
                    data.clear();
                    try {
                        JSONArray ja = new JSONObject(response.body().string()).getJSONArray("data");
                        for (int i = 0; i < ja.length(); i++) {
                            JSONObject jo = ja.getJSONObject(i);
                            data.add(new UserBean(jo.getString("nickname"),jo.getString("email"),jo.getString("account"),jo.getString("iconUrl")));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    adp.notifyDataSetChanged();
                });
            }
        });
        launcher=registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            int code=result.getResultCode();
            if (code == RESULT_OK) {
                Uri uri = result.getData().getData();
                File file = new File(uri.getPath());
                Glide.with(this).load(uri).apply(Utils.getGlideOption()).placeholder(R.drawable.loading).placeholder(R.drawable.loading).error(R.drawable.loaderr).into(binding.groupSettingIcon);
                binding.groupSettingIcon.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()));
                GroupPresenter.updateIconById(App.groupBean.id, file, new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {
                        e.printStackTrace();
                    }
                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) {
                    }
                });
            } else if (code == ImagePicker.RESULT_ERROR) {
                Utils.toast(ImagePicker.getError(result.getData()));
            }
        });
    }
}